const tokenFn = require('../tools/token')
const adminInfo = require('../asset/data/adminInfo.json')
const until = require('../until/until')
const path = require('path')
const fs = require('fs')

const managerRolesUrl = 'asset/data/managerRoles.json'
const managerRolesPath = path.join(__dirname, '../', managerRolesUrl)

const captcha = require('../tools/captcha')

let captchaValue = ''

const adminDao = {
  captcha: (req, res, next) => {
    const captcha = captcha()

    captchaValue = captcha.text

    res.type('svg')
    res.status(200).send(captcha.data)
    res.end()
  },

  login: async (req, res, next) => {
    console.log(req.body)
    const params = req.body

    if (!params) {
      res.json(until.formatter(500, '操作失败，请确认登录信息再重试'))
      return
    }

    if (params.username === 'admin' && params.password === '123456') {
      const token = await tokenFn.setToken(params.username, params.password)

      const tokenInfo = {
        tokenHead: 'Bearer',
        token,
      }

      res.json(until.formatter(200, '操作成功', tokenInfo))
    } else {
      res.json(until.formatter(400, '操作失败，请确认登录信息再重试'))
    }
  },
  info: (req, res, next) => {
    console.log(adminInfo)
    res.json(until.formatter(200, '操作成功', adminInfo))
  },
  role: (req, res, next) => {
    console.log(req.query)

    const params = req.query

    const managerRolesData = JSON.parse(
      fs.readFileSync(managerRolesPath).toString()
    )

    const managerRole = managerRolesData.find((item) => item.id == params.id)

    res.json(until.formatter(200, '操作成功', managerRole))
  },
  roleUpdate: (req, res, next) => {
    console.log(req.body)

    const params = req.body

    const managerRolesData = JSON.parse(
      fs.readFileSync(managerRolesPath).toString()
    )

    const index = managerRolesData.findIndex((item) => item.id === params.id)

    managerRolesData[index] = params

    const managerRolesDataStr = JSON.stringify(managerRolesData)

    fs.writeFile(managerRolesPath, managerRolesDataStr, (err) => {
      if (err) {
        console.error(err)
      }
      console.log('修改成功')
    })

    res.send('update')
  },
}

module.exports = adminDao
